package frame.options.simulation.create.coordinated;

import ilog.concert.IloException;
import ilog.cplex.IloCplex;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import com.nexes.wizard.WizardPanelDescriptor;

import frame.options.simulation.create.embedding.EmbeddingDescriptor;
import frame.options.simulation.create.nodes.NodesDescriptor;
import frame.options.simulation.create.splitting.SplittingDescriptor;

public class CoordinatedDescriptor extends WizardPanelDescriptor implements ActionListener
{
	public static final String IDENTIFIER = CoordinatedDescriptor.class.getSimpleName();
	
	private CoordinatedPanel coordinatedPanel;
	public CoordinatedPanel getCoordinatedPanel(){ return coordinatedPanel; }
	public void setCoordinatedPanel( CoordinatedPanel coordinatedPanel ){ this.coordinatedPanel = coordinatedPanel; }
	
	public CoordinatedDescriptor()
    {
		this.setCoordinatedPanel( new CoordinatedPanel() );
		this.getCoordinatedPanel().addListeners( this );
		
		this.setPanelDescriptorIdentifier( CoordinatedDescriptor.IDENTIFIER );
    	this.setPanelComponent( this.getCoordinatedPanel() );
    }
    
    @Override
	public Object getBackPanelDescriptor()
    {
    	return SplittingDescriptor.IDENTIFIER;
    }
    
    @Override
	public Object getNextPanelDescriptor()
    {
    	if( this.getCoordinatedPanel().getYesRadioButton().isSelected() )
    		return EmbeddingDescriptor.IDENTIFIER;
    	
    	else if( this.getCoordinatedPanel().getNoRadioButton().isSelected() )
    		return NodesDescriptor.IDENTIFIER;
    	
    	else
    		return null;
    }
    
    @Override
	public void aboutToDisplayPanel()
    {
    	this.setNextFinishButton();
    }
    
	@Override
	public void actionPerformed( ActionEvent actionEvent )
	{
		this.setNextFinishButton();
	}
	
	private void setNextFinishButton()
	{
		this.getCoordinatedPanel().getErrorLabel().setText( "" );
		this.getWizard().setNextFinishButtonEnabled( false );
		
		if( !this.isCplexInstalled() && this.getCoordinatedPanel().getYesRadioButton().isSelected() )
			this.getCoordinatedPanel().getErrorLabel().setText( "\"Yes\" is not selectable because Cplex is not installed" );
		
		else
			this.getWizard().setNextFinishButtonEnabled( true );
	}
	
	private boolean isCplexInstalled()
	{
		try
		{
			new IloCplex();

			return true;
		}
		catch( UnsatisfiedLinkError unsatisfiedLinkError )
		{
			return false;
		}
		catch( IloException e )
		{
			return false;
		}
	}
	
}
